package cn.manyufun.myf.ui.user.activity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.manyufun.myf.R;
import cn.manyufun.myf.api.Api;
import cn.manyufun.myf.api.HostType;
import cn.manyufun.myf.app.AppConstant;
import cn.manyufun.myf.bean.BaseBean;
import cn.manyufun.myf.bean.UserSummary;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.baserx.RxSchedulers;
import cn.manyufun.myf.common.baserx.RxSubscriber;
import cn.manyufun.myf.common.commonutils.ImageLoaderUtils;
import cn.manyufun.myf.common.commonutils.LogUtils;
import cn.manyufun.myf.common.commonutils.TimeUtil;
import cn.manyufun.myf.common.commonutils.ToastUtil;
import cn.manyufun.myf.common.commonutils.UserInfoUtils;
import cn.manyufun.myf.common.commonwidget.NormalTitleBar;
import cn.manyufun.myf.widget.actionsheet.ActionSheet;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static cn.manyufun.myf.common.commonutils.RequestBodyUtils.toRequestBody;
import static cn.manyufun.myf.common.commonutils.TimeUtil.dateFormatYMD;

public class ModifyActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.iv_user_logo)
    ImageView mIvUserLogo;
    @BindView(R.id.ev_nickname)
    EditText mEvNickName;
    @BindView(R.id.ev_slogan)
    EditText mEvSlogan;
    @BindView(R.id.sp_gender)
    Spinner mSpGender;
    @BindView(R.id.ev_birthday)
    TextView mTvBirthday;
    @BindView(R.id.tv_update_logo)
    TextView mTvUpdateLogo;

    private Uri photoUri;
    private String image_file = "";
    private File mHeadfile;

    @OnClick(R.id.ll_birthday)
    void showDatePicker() {
        showDatePickerDialog();
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_modify;
    }

    @Override
    public void initPresenter() {

    }

    public static void startAction(Context context) {
        Intent intent = new Intent(context, ModifyActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void initView() {
        UserSummary user = UserInfoUtils.getInstance().getUser();
        if (user == null) {
            Bundle bundle = new Bundle();
            bundle.putString(LoginAct.LOGIN_FROM, ModifyActivity.class.getSimpleName());
            LoginAct.startAction(this, bundle);
            return;
        }

        ImageLoaderUtils.displayRound(this, mIvUserLogo, user.HeadImgUrl);
        mEvNickName.setText(user.NickName);

        mSpGender.setSelection(user.Gender - 1);
        mEvSlogan.setText(user.Slogan);
        mTvBirthday.setText(TimeUtil.getStringByFormat(user.Birthday, dateFormatYMD));

        mTvUpdateLogo.setOnClickListener(this);

        ntb.setTitleText("编辑资料");
        ntb.setRightTitle("保存");
        ntb.setRightTitleVisibility(true);
        ntb.setOnBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ntb.setOnRightTextListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nickName = mEvNickName.getText().toString();
                String birthday = mTvBirthday.getText().toString();
                int gender = mSpGender.getSelectedItemPosition() + 1;
                String sLogan = mEvSlogan.getText().toString();
                String region = "";
//                if (TextUtils.isEmpty(content) || TextUtils.isEmpty(title)) {
//                    ToastUtil.showLong("请输入标题或评论内容！");
//                    return;
//                }
                Map<String, RequestBody> bodyMap = new HashMap<>();
                bodyMap.put("UserToken", toRequestBody(UserInfoUtils.getInstance().getToken()));
                bodyMap.put("NickName", toRequestBody(nickName));
                bodyMap.put("Gender", toRequestBody(gender + ""));
                bodyMap.put("Birthday", toRequestBody(birthday));
                bodyMap.put("Region", toRequestBody(region));
                bodyMap.put("Slogan", toRequestBody(sLogan));


                MultipartBody.Part body = null;
                if (mHeadfile != null) {
                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), mHeadfile);
                    body = MultipartBody.Part.createFormData("image", mHeadfile.getName(), requestBody);
                }

//                Api.getDefault(HostType.manyufun).updateUser(UserInfoUtils.getInstance().getToken(), nickName, gender, "2011-11-11", region, sLogan,body)
                Api.getDefault(HostType.manyufun).updateUserMap(bodyMap, body)
                        .compose(RxSchedulers.<BaseBean>io_main())
                        .subscribe(new RxSubscriber<BaseBean>(ModifyActivity.this, false) {
                            @Override
                            public void onStart() {
                                startProgressDialog();
                                super.onStart();
                            }

                            @Override
                            protected void _onNext(BaseBean posterBean) {
                                if (posterBean.getSuccess().equals("1")) {
                                    ToastUtil.show("提交成功", 3);

//                                    mRxManager.post(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, null);
                                    finish();
                                } else {
                                    ToastUtil.show(posterBean.getErrorMsg(), 3);
                                }
                                LogUtils.logd("xwx_modify:" + posterBean.getSuccess() + "|" + posterBean.getErrorCode());
                                stopProgressDialog();
                            }

                            @Override
                            protected void _onError(String message) {
                                stopProgressDialog();
                                LogUtils.logd("xwx_modifyerror:" + message);
                            }
                        });
//                Api.getDefault(HostType.manyufun).imageUpload(body)
//                        .compose(RxSchedulers.<ImageUploadBean>io_main())
//                        .subscribe(new RxSubscriber<ImageUploadBean>(ModifyActivity.this, false) {
//                            @Override
//                            public void onStart() {
//                                super.onStart();
//                            }
//
//                            @Override
//                            protected void _onNext(ImageUploadBean posterBean) {
//                                if (posterBean.getSuccess().equals("1")) {
//                                    ToastUtil.show("提交成功", 3);
//                                    LogUtils.logd("xwx_upload"+posterBean.ImageUrl);
////                                    mRxManager.post(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, null);
////                                    finish();
//                                } else {
//                                    ToastUtil.show(posterBean.getErrorMsg(), 3);
//                                }
//                            }
//
//                            @Override
//                            protected void _onError(String message) {
//
//                            }
//                        });

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case AppConstant.REQUEST_CODE_READ_EXTERNAL_STORAGE:
                boolean flag = true;
                for (int grantResult : grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        flag = false;
                        break;
                    }
                }
                if (!flag) {
//                    mTvUpdateLogo.setOnClickListener(this);
                    ToastUtil.showLong("没有该权限无法修改头像！");
                } else {
                    upload_images();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkReadStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            int checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCameraPermission != PackageManager.PERMISSION_GRANTED || checkReadStoragePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, AppConstant.REQUEST_CODE_READ_EXTERNAL_STORAGE);
            } else {
                upload_images();
            }
        } else {
            upload_images();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstant.RESULT_LOAD_IMAGE || requestCode == AppConstant.RESULT_LOAD_CAMERA) {
            String picturePath = "";
            Uri selectedImage = null;
            if (requestCode == AppConstant.RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
                selectedImage = data.getData();
            } else if (requestCode == AppConstant.RESULT_LOAD_CAMERA) {
                selectedImage = photoUri;
            }
//            根据图库返回的数据类型分别处理（比如小米的照片文件夹返回的就是file类型，其他图片返回的时content类型，需要另外处理）
            if (selectedImage == null) {
                return;
            }
            if (selectedImage.getScheme().equals("file")) {
                picturePath = selectedImage.toString().replace("file://", "");
            } else if (selectedImage.getScheme().equals("content")) {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                if (cursor == null) //throw new NullPointerException("没找到照片");
                    return;
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                }
                cursor.close();
            }
            if (!picturePath.equals("")) {
                File file = new File(picturePath);
                if (!file.exists()) {
                    return;
                }
//                先释放内存

                lubanCompress(picturePath);//CompressUtils.Compress(this, picturePath, Bitmap.CompressFormat.JPEG, 800);

            }
        }
    }

    private void lubanCompress(String path) {
        Luban.with(this)
                .load(path)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        LogUtils.logd("xwx commpress start.");
                    }

                    @Override
                    public void onSuccess(File file) {
                        compressSuccess(file);
                    }

                    @Override
                    public void onError(Throwable e) {

                        LogUtils.logd("xwx commpress error." + e.toString());
                    }
                }).launch();

    }

    private void compressSuccess(File file) {
        image_file = file.getAbsolutePath();
        LogUtils.logd("xwx commpress success." + image_file);
        mHeadfile = file;
        ImageLoaderUtils.displayRound(this, mIvUserLogo, file);
//        mIvUserLogo.setImageBitmap(BitmapFactory.decodeFile(image_file));
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/myf/compressimage/";
        File file = new File(path);
        LogUtils.logd("xwx commpress get path." + path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private void upload_images() {
        final ActionSheet actionSheet = new ActionSheet(this);
        actionSheet.show("选择图片来源", new String[]{"拍照", "从相册选择"}, new cn.manyufun.myf.widget.actionsheet.Method.Action1<Integer>() {
            @Override
            public void invoke(Integer index) {
                actionSheet.hide();
                if (index == 0) {
                    String sdState = Environment.getExternalStorageState();
                    if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                        Toast.makeText(ModifyActivity.this, "没有存储卡", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    ContentValues values = new ContentValues();
                    photoUri = ModifyActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                    startActivityForResult(intent, AppConstant.RESULT_LOAD_CAMERA);
                } else if (index == 1) {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, AppConstant.RESULT_LOAD_IMAGE);
                }
            }
        });

    }

    private void showDatePickerDialog() {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
            // TODO Auto-generated method stub
            mTvBirthday.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }
}
